/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2021. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.hannesdorfmann.mosby3.mvp.delegate;

import com.hannesdorfmann.mosby3.PresenterManager;
import com.hannesdorfmann.mosby3.mvp.MvpAbility;
import com.hannesdorfmann.mosby3.mvp.MvpPresenter;
import com.hannesdorfmann.mosby3.mvp.MvpView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;

import java.util.UUID;

/**
 * The default implementation of {@link AbilitySliceMvpDelegate}
 * Presenter is available (has view that is attached) in {@link #onStart(Intent)} ()} (after
 * super.onViewCreated() is called). View will be detached in {@link #onStop()} ()} from presenter,
 * and eventually presenter will be destroyed in {@link #onStop()}.
 *
 * @param <V> The type of {@link MvpView}
 * @param <P> The type of {@link MvpPresenter}
 * @see AbilitySliceMvpDelegate
 */
public class AbilitySliceMvpDelegateImpl<V extends MvpView, P extends MvpPresenter<V>>
    implements AbilitySliceMvpDelegate<V, P> {

  public final String TAG = AbilitySliceMvpDelegateImpl.class.getSimpleName();
  HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0, TAG);
  protected static final String KEY_MOSBY_VIEW_ID = "com.hannesdorfmann.mosby3.fragment.mvp.id";

  public final static boolean DEBUG = false;
  private static final String DEBUG_TAG = "FragmentMvpVSDelegate";

  private MvpDelegateCallback<V, P> delegateCallback;
  protected AbilitySlice fragment;
  protected final boolean keepPresenterInstanceDuringScreenOrientationChanges;
  protected final boolean keepPresenterOnBackstack;
  private boolean onViewCreatedCalled = false;
  protected String mosbyViewId;

  /**
   * @param fragment The Fragment
   * @param delegateCallback the DelegateCallback
   * @param keepPresenterDuringScreenOrientationChange true, if the presenter should be kept during
   * screen orientation
   * changes. Otherwise, false
   * @param keepPresenterOnBackstack true, if the presenter should be kept when the fragment is
   * destroyed because it is put on the backstack, Otherwise false
   */
  public AbilitySliceMvpDelegateImpl(AbilitySlice fragment,
      MvpDelegateCallback<V, P> delegateCallback,
      boolean keepPresenterDuringScreenOrientationChange, boolean keepPresenterOnBackstack) {

    if (delegateCallback == null) {
      throw new NullPointerException("MvpDelegateCallback is null!");
    }

    if (fragment == null) {
      throw new NullPointerException("Fragment is null!");
    }

    if (!keepPresenterDuringScreenOrientationChange && keepPresenterOnBackstack) {
      throw new IllegalArgumentException("It is not possible to keep the presenter on backstack, "
          + "but NOT keep presenter through screen orientation changes. Keep presenter on backstack also "
          + "requires keep presenter through screen orientation changes to be enabled");
    }

    this.fragment = fragment;
    this.delegateCallback = delegateCallback;
    this.keepPresenterInstanceDuringScreenOrientationChanges =
        keepPresenterDuringScreenOrientationChange;
    this.keepPresenterOnBackstack = keepPresenterOnBackstack;
  }

  /**
   * Generates the unique (mosby internal) view id and calls {@link
   * MvpDelegateCallback#createPresenter()}
   * to create a new presenter instance
   *
   * @return The new created presenter instance
   */
  private P createViewIdAndCreatePresenter() {
    P presenter = delegateCallback.createPresenter();
    if (presenter == null) {
      throw new NullPointerException(
          "Presenter returned from createPresenter() is null. Activity is " + getActivity());
    }
    if (keepPresenterInstanceDuringScreenOrientationChanges) {
      mosbyViewId = UUID.randomUUID().toString();
      PresenterManager.putPresenter(getActivity(), mosbyViewId, presenter);
    }
    return presenter;
  }



  private Ability getActivity() {
    Ability activity = fragment.getAbility();
    if (activity == null) {
      throw new NullPointerException(
          "Activity returned by Fragment.getActivity() is null. Fragment is " + fragment);
    }

    return activity;
  }

  private P getPresenter() {
    P presenter = delegateCallback.getPresenter();
    if (presenter == null) {
      throw new NullPointerException("Presenter returned from getPresenter() is null");
    }
    return presenter;
  }

  private V getMvpView() {
    V view = delegateCallback.getMvpView();
    if (view == null) {
      throw new NullPointerException("View returned from getMvpView() is null");
    }
    return view;
  }

  static boolean retainPresenterInstance(Ability activity, AbilitySlice fragment,
      boolean keepPresenterInstanceDuringScreenOrientationChanges,
      boolean keepPresenterOnBackstack) {

    if (activity.isUpdatingConfigurations()) {
      return keepPresenterInstanceDuringScreenOrientationChanges;
    }

    if (activity.isTerminating()) {
      return false;
    }

    if (keepPresenterOnBackstack /*&& BackstackAccessor.isFragmentOnBackStack(fragment)*/) {
      return true;
    }

    return false;
  }

  @Override
  public void onStart(Intent intent) {

    P presenter = null;

    {
      presenter = createViewIdAndCreatePresenter();
      if (DEBUG) {
        HiLog.error(LABEL,  "New presenter " + presenter + " for view " + getMvpView());
      }
    }

    if (presenter == null) {
      StringBuilder sb = new StringBuilder();
      sb.append(MvpAbility.BASE_URL);
      sb.append(MvpAbility.ISSURE);
      throw new IllegalStateException(
              "Oops, Presenter is null. This seems to be a Mosby internal bug. Please report this issue here: "+ sb.toString());
    }

    delegateCallback.setPresenter(presenter);

    getPresenter();
    presenter.attachView(getMvpView());

    if (DEBUG) {
      HiLog.error(LABEL,  "View" + getMvpView() + " attached to Presenter " + presenter);
    }

    onViewCreatedCalled = true;
  }

  @Override
  public void onActive() {

  }

  @Override
  public void onInactive() {

  }

  @Override
  public void onForeground(Intent intent) {
  }

  @Override
  public void onBackground() {
    onViewCreatedCalled = false;

    getPresenter().detachView();

    if (DEBUG) {
      HiLog.error(LABEL,  "detached MvpView from Presenter. MvpView "
              + delegateCallback.getMvpView()
              + "   Presenter: "
              + getPresenter());
    }
  }

  @Override
  public void onStop() {
    boolean retainPresenterInstance = retainPresenterInstance(getActivity(), fragment,
            keepPresenterInstanceDuringScreenOrientationChanges, keepPresenterOnBackstack);

    P presenter = getPresenter();
    if (!retainPresenterInstance) {
      presenter.destroy();
      if (DEBUG) {
        HiLog.error(LABEL,  "Presenter destroyed. MvpView "
                + delegateCallback.getMvpView()
                + "   Presenter: "
                + presenter);
      }
    }

    if (!retainPresenterInstance && mosbyViewId != null) {
      PresenterManager.remove(getActivity(), mosbyViewId);
    }
  }

}
